<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <button>按钮</button>
  <input type="file">
  <hr>
  <img src="../src/assets/images/avatar.jpg" alt="" width="350">

  <script>
    const button = document.querySelector('button')
    const input = document.querySelector('input')
    const img = document.querySelector('img')

    button.addEventListener('click', function () {
      input.click()
    })

    input.addEventListener('change', function () {
      let file = input.files[0]

      if (input.files.length > 0) {
        // 第一种方法
        // let url = URL.createObjectURL(file)
        // img.src = url


        // 第二种方法
        let fr = new FileReader()
        fr.readAsDataURL(file)
        fr.onload = function () {
          // fr.result 就是base64格式的字符串
          img.src = fr.result
        }
      }
    })

  </script>

</body>

</html>